package com.atguigu.com.nio.nio_4_群聊;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Date;
import java.util.Iterator;

/**
 * @Author: robert.song
 * @Date: Created in 2021/8/11
 */
public class GroupChatServer {
    //    定义属性
    private Selector selector;
    private ServerSocketChannel listenChannel;
    private static final int PORT = 6667;

    //    构造器
//    初始化工作
    public GroupChatServer() {
        try {
//            得到选择器
            selector = Selector.open();
//            serversocketChannel
            listenChannel = ServerSocketChannel.open();
//            绑定端口
            listenChannel.socket().bind(new InetSocketAddress(PORT));
//            设置非阻塞模式
            listenChannel.configureBlocking(false);
//            将该listenChannel 注册到selector
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //    监听
    public void listen() {
        try {
//            循环处理
            while (true) {
                int count = selector.select(2000);
                if (count > 0) {
//                    遍历的说道selectionKey集合
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
//                        取出selectionKey
                        SelectionKey key = iterator.next();
//                        监听accept
                        if (key.isAcceptable()) {
                            SocketChannel sc = listenChannel.accept();
//                            设置非阻塞 否则报错：java.nio.channels.IllegalBlockingModeException
                            sc.configureBlocking(false);
                            sc.register(selector, SelectionKey.OP_READ);
                            System.out.println(new Date() + ":" + sc.getRemoteAddress() + "已上线");
                        }
                        if (key.isReadable()) {
//                            通道发生read事件，即通道是可读状态
//                            处理读
                            readData(key);
                        }
//                        当前的key删除，防止重复处理
                        iterator.remove();
                    }
                } else {
                    System.out.println("等待。。。");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //    读消息
    public void readData(SelectionKey key) {
//        定义一个SocketChannel
        SocketChannel channel = null;
        try {
//            取得关联的channel
            channel = (SocketChannel) key.channel();
//            创建buffer
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            int count = channel.read(byteBuffer);
//            根据count的值做处理
            if (count > 0) {
//                把缓冲区的数据转成字符串
                String msg = new String(byteBuffer.array());
//                输出该消息
                System.out.println("from 客户端：" + msg);
//                向其它的客户端转发消息
                sendInfoToOtherClients(msg, channel);
            }
        } catch (IOException e) {
            try {
                System.out.println(channel.getRemoteAddress() + "has off line");
                key.cancel();
            } catch (IOException ex) {
                ex.printStackTrace();
            } finally {
                try {
                    channel.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    //    转发消息给其他客户（找通道,去除自己）
    private void sendInfoToOtherClients(String msg, SocketChannel self) throws IOException {
        System.out.println("服务器转发消息中...");
//        遍历 所有注册到selector的socketChannel并排除自己即self
        for (SelectionKey key : selector.keys()) {
//            通过key取出对应的SocketChannel
            Channel targetChannel = key.channel();
//            排除自己
            if (targetChannel instanceof SocketChannel && targetChannel != self) {
//                转型
                SocketChannel dest = (SocketChannel) targetChannel;
//                将msg存储到buffer
                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
//                将buffer的数据写入通道
                dest.write(buffer);
            }
        }
    }

    public static void main(String[] args) {
//        创建服务器对象
        GroupChatServer groupChatServer = new GroupChatServer();
        groupChatServer.listen();
    }
}
